# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render

# Create your views here.


import os
import time

import django
import xlrd

# os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'EDM.settings')  # 在Django 里想单独执行文件写上这句话
# django.setup()  # 执行

from django.utils.encoding import smart_str
from django_redis import get_redis_connection

from core.models import EDMTasksCache, EDMTasks

from django.db import connection


def clean_edm_tasks_cache():
    cursor = connection.cursor()
    cursor.execute("delete from edm_tasks_cache")
    cursor.close()


def import_edm_tasks_cache(request):
    err_str = ''
    kwargs2SQL_list = []
    # with open('my_rymmx.xlsx') as f:
    #     content = f.read()
    fobj = request.FILES.get("upload")
    # fobj = request.data.get("upload")
    if not fobj:
        return [], u'请先选择文件'
    content = fobj.read()
    try:
        workbook = xlrd.open_workbook(filename=None, file_contents=content)
        table = workbook.sheets()[0]
        subject_template = table.row_values(0)[0]
        content_template = table.row_values(1)[0]
        # print table.row_values(2)
        # print subject_template
        # print content_template
        for line in range(3, table.nrows):
            EMAIL, NAME, V1, V2, V3, V4, V5, V6, V7, V8 = table.row_values(line)
            kwargs = {
                'EMAIL': EMAIL,
                'NAME': NAME,
                'V1': V1,
                'V2': V2,
                'V3': V3,
                'V4': V4,
                'V5': V5,
                'V6': V6,
                'V7': V7,
                'V8': V8,
            }
            # print EMAIL, NAME, V1, V2, V3, V4, V5, V6, V7, V8
            subject = subject_template.format(**kwargs)
            content = content_template.format(**kwargs)
            # print subject
            # print content

            kwargs2SQL = {
                'email': EMAIL,
                'subject': subject,
                'content': content,
            }

            kwargs2SQL_list.append(kwargs2SQL)
    except Exception as e:
        print e.message
        try:
            err_str = u"表格第 %s 行 格式有误，请修正后重新上传" % (line)
            # print u"表格第 %s 行 格式有误，请修正后重新上传" % (line)
        except:
            err_str = u"表格格式有误请修正后重新上传"
            # print u"表格格式有误请修正后重新上传"

    if err_str:
        kwargs2SQL_list = []

    return kwargs2SQL_list, err_str


def import_edm_tasks():
    objs = EDMTasksCache.objects.all()
    for obj in objs:
        kwargs = {
            'email': obj.email,
            'subject': obj.subject,
            'content': obj.content,
            'batch_id': obj.batch_id,
            'result': 'wait',
        }
        EDMTasks.objects.create(**kwargs)
    return objs.count()


def edm_tasks():
    redis = get_redis_connection()
    batch_id = redis.get('EDM:batch_id')
    tasks_count = {

        'all': EDMTasks.objects.all().count(),
        'wait': EDMTasks.objects.filter(result="wait").count(),
        'success': EDMTasks.objects.filter(result="success").count(),
        "failure": EDMTasks.objects.filter(result="failure").count(),

        'all_new': EDMTasks.objects.filter(batch_id=batch_id).count(),
        'wait_new': EDMTasks.objects.filter(batch_id=batch_id, result="wait").count(),
        'success_new': EDMTasks.objects.filter(batch_id=batch_id, result="success").count(),
        "failure_new": EDMTasks.objects.filter(batch_id=batch_id, result="failure").count(),
    }
    return tasks_count


def home(request):
    redis = get_redis_connection()
    context = {
        'table': {},
        'secc_lines': 0,
        'err': '',
        'import_edm_tasks': 0,
        'edm_tasks': {},
    }

    if request.method == 'POST':
        clean_edm_tasks_cache()
        secc_lines, err_str = import_edm_tasks_cache(request)
        if err_str:
            context['err'] = err_str
        else:
            if secc_lines:
                context['secc_lines'] = len(secc_lines)
                context['table'] = secc_lines[0]
                batch_id = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + "_" + str(len(secc_lines))
                redis.set('EDM:batch_id', batch_id)
                for i in secc_lines:
                    i['batch_id'] = batch_id
                    EDMTasksCache.objects.create(**i)

    if request.GET.get("submit") == 'submit':
        count = import_edm_tasks()
        context['import_edm_tasks'] = count
        clean_edm_tasks_cache()

    edm_from_name = request.GET.get("edm_from_name")
    if edm_from_name:
        if edm_from_name == '0':
            redis.delete('EDM:from_name')
        else:
            redis.set('EDM:from_name', edm_from_name)

    context['edm_tasks'] = edm_tasks()
    context['batch_id'] = redis.get('EDM:batch_id')
    context['edm_tasks_count'] = redis.get('EDM:edm_tasks_count')
    context['edm_from_name'] = redis.get('EDM:from_name')
    return render(request, 'edm.html', context=context)


if __name__ == '__main__':
    clean_edm_tasks_cache()
    secc_lines, err_lines = import_edm_tasks_cache("123456")
    import_edm_tasks()
    # err_lines = inport_edm_tasks_cache()
    print secc_lines
    print err_lines
